package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"studygin-2/model"
)

type ReqRegister struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type ReqLogin struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

func Login(c *gin.Context) {
	var req ReqLogin
	if err := c.ShouldBindBodyWithJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	user := model.User{
		Username: req.Username,
		Password: req.Password,
	}
	token, err := model.LoginCheck(user.Username, user.Password)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"token": token, "message": "success"})
}

func Register(c *gin.Context) {
	var req ReqRegister
	if err := c.ShouldBindBodyWithJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"data": err.Error(),
		})
		return
	}
	user := model.User{Username: req.Username, Password: req.Password}
	_, err := user.SaveUser()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"data": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "register success",
		"data":    req,
	})
}
